const link = require("walt-link");
const fs = require("fs");
const buildTools = require("walt-buildtools");
const path = require("path");

module.exports = function wrap(filepath) {
  const builder = link(filepath);

  const tree = Object.assign({}, builder.tree, {
    opcodes: Object.entries(builder.tree.opcodes).reduce((a, [k, v]) => {
      const uint8View = new Uint8Array(v);
      const result = Object.assign(a, {
        [k]: Array.from(uint8View)
      });
      return result;
    }, {})
  });

  return `
// This file is auto-generated by walt-cli --wrap
const tree = ${JSON.stringify(tree)};

// Serialized binary needs to be converted back to an array buffer
tree.opcodes = Object.entries(tree.opcodes).reduce((a, [k, v]) => {
  return Object.assign(a, {
    [k]: new Uint8Array(v).buffer
  });
}, {});

// Injected build method from 'walt-buildtools' package
${buildTools.build.toString()}

// Factory method
module.exports = function(importsObj) {
  return build(importsObj, tree);
};
`;
};
